const app = getApp()
const adapters = require("../../utils/adapters");
import eventBus from '../../utils/eventBus';
import Toast from '@vant/weapp/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    header: {
      title: '连接电池',
      whiteBg: false,
      mode: 'back',
      navBarHeight: app.globalData.navBarHeight,
      tabbarHeight: app.globalData.tabbarHeight,
      screenHeight: app.globalData.screenHeight
    },
    searchBar: {
      value: ''
    },
    scanBloothDevices: {
      isScanning: false,
    },
    bloothDeviceList: [],
    connectTarget: {
      deviceId: '',
      connectStatus: false,
      serviceUUID: "0000fff0-0000-1000-8000-00805f9b34fb",
      serviceUUIDForA4: "0000fee7-0000-1000-8000-00805f9b34fb",
      notifyUUID: "0000fff1-0000-1000-8000-00805f9b34fb",
      notifyUUIDForA4: "000036f6-0000-1000-8000-00805f9b34fb",
      writeUUID: "0000fff2-0000-1000-8000-00805f9b34fb",
      writeUUIDForA4: "000036f5-0000-1000-8000-00805f9b34fb",
      parametersList: [
        "4d530301010058000d0a", // SN
        "4d530302010059000d0a", // 版本
        "4d53030501005c000d0a", // 单节电压
        "4d53030601005d000d0a", // 总电压、电流
        "4d53030801005f000d0a", // 读取均衡状态
        "4d530309010060000d0a",
        "4d530311010068000d0a",
        "4d53031401006b000d0a",
        "4d53031801006f000d0a",
        "4d530319010070000d0a",
        "4d530320010077000d0a",
        "4d530322010079000d0a",
        "4d53032301007a000d0a",
        "4d53032401007b000d0a",
        "4d53030701005e000d0a",
        "4d530301010058000d0a", // SN
      ],
    },
  },
  onPageScroll(e) {
    this.setData({
      'header.whiteBg': e.scrollTop < 40 ? false : true,
    })
  },
  
  onLoad(options) {

  },

  onUnload() {
    // 停止蓝牙设备搜索
    wx.stopBluetoothDevicesDiscovery({
      success(res) {
        console.log('蓝牙设备搜索已停止', res);
      }
    });
    
    // 如果有已连接的设备，则断开连接
    if (this.connectedDeviceId) {
      wx.closeBLEConnection({
        deviceId: this.connectedDeviceId,
        success(res) {
          console.log('已断开蓝牙设备连接', res);
        }
      });
    }

    // 关闭蓝牙模块
    wx.closeBluetoothAdapter({
      success(res) {
        console.log('蓝牙模块已关闭', res);
      }
    });
  },

  searchBarOnChange(e) {
    this.setData({
      "searchBar.value": e.detail
    })
  },

  searchBarOnSearch() {
    let bloothDeviceList = this.data.bloothDeviceList
    const target = this.data.searchBar.value
    bloothDeviceList.forEach(device => {
      device.show = device.deviceId.includes(target)
    })
    this.setData({
      bloothDeviceList: bloothDeviceList
    })
  },

  scanQRCode() {
    wx.scanCode({
      success: (res) => { 
        console.log('扫描结果:', res.result);
        this.setData({ 
          'searchBar.value': res.result,
        });
        this.searchBarOnSearch();
      },
      fail: (err) => {
        console.log('扫码失败:', err);
        wx.showToast({
          title: '扫码失败，请重试',
          icon: 'none',
        })
      }
    })
  },

  /**
   * 以下内容为蓝牙相关（扫描，连接，获取报文）
   */

  scanBloothDevices() {
    if (this.data.scanBloothDevices.isScanning) {
      // 如果正在扫描，就停止扫描
      wx.stopBluetoothDevicesDiscovery({
        success: () => {
          console.log('蓝牙扫描已停止');
          this.setData({
            "scanBloothDevices.isScanning": false,
          });
        },
        fail: (err) => {
          console.error('停止扫描失败', err);
        }
      });
      return;
    }
    wx.openBluetoothAdapter({
      success: () => {
        console.log('蓝牙适配器初始化成功');
        this.setData({
          "scanBloothDevices.isScanning": true,
        })
  
        wx.startBluetoothDevicesDiscovery({
          success: () => {
            console.log('开始搜索蓝牙设备');
          }
        });

        const searchVal = this.data.searchBar.value.toLowerCase();
  
        wx.onBluetoothDeviceFound((devices) => {
          
          const newDevices = devices.devices.filter(device => {
            return device.deviceId &&
                    device.name !== "" &&
                    !this.data.bloothDeviceList.some(item => item.deviceId === device.deviceId);
          });
          
          const updatedList = [
              ...this.data.bloothDeviceList,
              ...newDevices.map(device => ({
                  deviceId: device.deviceId,
                  name: device.name,
                  show: searchVal === '' || device.deviceId.includes(searchVal)
              }))
          ];
          
          this.setData({
              bloothDeviceList: updatedList
          });
  
        });
      },
      fail: (err) => {
        console.error('初始化蓝牙适配器失败', err);
        this.setData({
          "scanBloothDevices.isScanning": false,
        })
      }
    });
  },

  async connectBloothDevice(e) {
    const connectStatus = this.data.connectTarget.connectStatus
    const deviceId = e.currentTarget.dataset.deviceid
    const deviceName = this.data.bloothDeviceList.find(device => device.deviceId === deviceId).name
    const toast = Toast.loading({
      duration: 0, // 持续展示 toast
      forbidClick: true,
      message: '检测目标中...',
      selector: '#van-toast',
    });
    this._connectionToast = toast;
    if(connectStatus) {
      this.setData({
        "connectTarget.connectStatus": false
      });

      // 断开蓝牙设备连接
      wx.closeBLEConnection({
        deviceId: this.data.connectTarget.deviceId,
        success:(res) => {
          console.log('断开蓝牙设备连接成功', res);
          this._connectionToast.setData({ message: '断开蓝牙设备连接成功！', });
        },
        fail:(err) => {
          console.error('断开蓝牙设备连接失败', err);
          this._connectionToast.setData({ message: '断开蓝牙设备连接失败！', });
        }
      });
      if(this.data.connectTarget.deviceId === deviceId) {
        setTimeout(() => {
          this._connectionToast.clear();
        }, 2000);
        return
      }
    }
    console.log('开始连接设备,目标:' + deviceId);

    const notice = await adapters.sendConnectInfoToServer(deviceId)
    if(!notice.success){
      this._connectionToast.setData({ message: '操作失败！' + notice.msg, });
      setTimeout(() => {
        this._connectionToast.clear();
      }, 2000);
      return
    }

    // 发送设备id到主页，用于主页查看数据
    eventBus.emit('device', {deviceId, name: deviceName});

    this.setData({ "connectTarget.deviceId": deviceId })
  
    wx.createBLEConnection({
      deviceId,
      success: () => {
        console.log('BLE 连接成功');
        this._connectionToast.setData({
          message: 'BLE 连接成功',
        });
        this.setData({
          "connectTarget.connectStatus": true
        })
        wx.getBLEDeviceServices({
          deviceId,
          success: res => {
            console.log('服务:', res.services);
            this._connectionToast.setData({
              message: '已获取到服务',
            });
  
            wx.getBLEDeviceCharacteristics({
              deviceId,
              serviceId: deviceId.startsWith('A4') ? this.data.connectTarget.serviceUUIDForA4 : this.data.connectTarget.serviceUUID,
              success: res => {
                console.log('特征值:', res.characteristics);
                this._connectionToast.setData({
                  message: '已获取到特征值',
                });
                this.enableNotify(deviceId);
              },
              fail: err => {
                this._connectionToast.setData({ message: '获取特征值失败！请重试！', });
                setTimeout(() => {
                  this._connectionToast.clear();
                }, 2000);
                console.error('获取特征值失败！请重试！', err);
              }
            });
  
          },
          fail: err => {
            this._connectionToast.setData({ message: '获取服务失败！请重试！', });
            setTimeout(() => {
              this._connectionToast.clear();
            }, 2000);
            console.error('获取服务失败！请重试！', err);
          }
        });
  
      },
      fail: err => {
        this._connectionToast.setData({ message: '连接失败！请重试！', });
        setTimeout(() => {
          this._connectionToast.clear();
        }, 2000);
        console.error('蓝牙连接失败', err);
      }
    });
  },

  async enableNotify(deviceId) {
    const serviceId = deviceId.startsWith('A4') ? this.data.connectTarget.serviceUUIDForA4 : this.data.connectTarget.serviceUUID;
    const characteristicId = deviceId.startsWith('A4') ? this.data.connectTarget.notifyUUIDForA4 : this.data.connectTarget.notifyUUID;
  
    if (!serviceId || !characteristicId) {
      console.error('serviceId 或 characteristicId 不存在');
      this._connectionToast.setData({ message: '服务或特征值不存在！', });
      setTimeout(() => {
        this._connectionToast.clear();
      }, 2000);
      return;
    }
  
    wx.notifyBLECharacteristicValueChange({
      deviceId,
      serviceId,
      characteristicId,
      state: true,
      success: () => {
        console.log('通知已开启');
        if (this._connectionToast) {
          this._connectionToast.setData({
            message: '启用通知成功，准备通信...',
          });
        }
        this._connectionToast.setData({ message: '连接成功！正在获取数据...', });
        this.sendCommands(deviceId);
      },
      fail: err => {
        console.error('开启通知失败', err);
        this._connectionToast.setData({ message: '开启通知失败！请重试！', });
        setTimeout(() => {
          this._connectionToast.clear();
        }, 2000);
      },
      complete: () => {
        // 可选：无论成功/失败都会执行
        console.log('开启通知操作完成');
      }
    });
  
    // 监听设备返回数据
    wx.onBLECharacteristicValueChange(async (res) => {
      const dataInfo = this.ab2hex(res.value)
      console.log('收到数据:', dataInfo)
      // 发送数据到服务器
      await adapters.sendCommandExecuteResult(deviceId, dataInfo)
    });
  },

  async sendCommands(deviceId) {
    let index = 0;
    const getCommandRes = await adapters.getCommand(deviceId)
    var stringArray = []
    if(getCommandRes.success) {
      stringArray = getCommandRes.orderList
    }else {
      this._connectionToast.setData({ message: '指令获取失败！请检查网络后重试！', });
      setTimeout(() => {
        this._connectionToast.clear();
      }, 2000);
      return
    }
    const sendNext = () => {
      if (index >= stringArray.length) return;
  
      const cmdHex = stringArray[index++];
      const buffer = new ArrayBuffer(cmdHex.length / 2);
      const dataView = new DataView(buffer);
  
      for (let i = 0; i < cmdHex.length; i += 2) {
        dataView.setUint8(i / 2, parseInt(cmdHex.substr(i, 2), 16));
      }
  
      wx.writeBLECharacteristicValue({
        deviceId: deviceId,
        serviceId: deviceId.startsWith('A4') ? this.data.connectTarget.serviceUUIDForA4 : this.data.connectTarget.serviceUUID,
        characteristicId: deviceId.startsWith('A4') ? this.data.connectTarget.writeUUIDForA4 : this.data.connectTarget.writeUUID,
        value: buffer,
        success: () => {
          console.log('指令发送成功:', cmdHex);
          setTimeout(sendNext, 700);
        },
        fail: err => {
          console.error('写入失败', err);
          setTimeout(sendNext, 1000);
        }
      });
    };
  
    sendNext();

    this._connectionToast.setData({ message: '数据获取完成！', });
    setTimeout(() => {
      this._connectionToast.clear();
    }, 2000);
  },

  ab2hex(buffer) {
    const hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      byte => ('0' + byte.toString(16)).slice(-2)
    );
    return hexArr.join('');
  },
})